package com.nanbei.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassDescription: 公平锁和不公平锁
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/9/26 17:32
 */
public class ReentrantLockDemo1 {
    public static void main(String[] args) {
        People people = new People();
        new Thread(()-> { for (int i = 0; i < 50; i++) people.pay(); },"a").start();
        new Thread(()-> { for (int i = 0; i < 50; i++) people.pay(); },"b").start();
        new Thread(()-> { for (int i = 0; i < 50; i++) people.pay(); },"c").start();
    }
}

class People{
    private int size = 50;

    // 默认为非公平锁，加上参数true后为公平锁
    ReentrantLock lock = new  ReentrantLock(true);

    public void pay(){
        lock.lock();
        try{
            if (size > 0){
                System.out.println(Thread.currentThread().getName()+"卖出第:\t"+(size--)+"\t 还剩下:"+size);
            }
        }finally {
            lock.unlock();
        }
    }
}
